Page({
  data: {
    cameraActive: true,
    devicePosition: 'back',
    tempFilePath: '',
    result: null,
    loading: false
  },
  
  takePhoto: function() {
    const ctx = wx.createCameraContext()
    this.setData({ loading: true })
    
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        if (!res.tempFilePath) {
          // 如果拍照接口返回的tempFilePath无效，尝试使用chooseImage
          wx.chooseImage({
            count: 1,
            sizeType: ['original'],
            sourceType: ['camera'],
            success: (chooseRes) => {
              this.uploadImage(chooseRes.tempFilePaths[0])
            },
            fail: (err) => {
              console.error('选择图片失败:', err)
              wx.showToast({ title: '获取图片失败', icon: 'none' })
              this.setData({ loading: false })
            }
          })
          return
        }
        this.uploadImage(res.tempFilePath)
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        wx.showToast({ title: '拍照失败', icon: 'none' })
        this.setData({ loading: false })
      }
    })
  },

  // 新增独立的上传方法
  uploadImage: function(filePath) {
    this.setData({
      tempFilePath: filePath,
      cameraActive: false,
      loading: true
    });
    
    wx.uploadFile({
      url: 'https://d6b4-2408-8214-591d-c3d0-e011-4bc6-8965-5fa1.ngrok-free.app/upload',
      filePath: filePath,
      name: 'file',
      success: (res) => {
        try {
          const result = JSON.parse(res.data);
          console.log('服务器返回数据:', result); // 调试日志
          
          if (result && result.success) {
            this.setData({ 
              result: {
                predictedClass: result.data.predictedClass || '未知类别',
                confidence: result.data.confidence || 0,
                imageUrl: result.data.imageUrl || ''
              },
              loading: false 
            });
          } else {
            wx.showToast({ 
              title: result?.message || '识别失败', 
              icon: 'none'
            });
          }
        } catch (e) {
          console.error('解析错误:', e, '原始数据:', res.data);
          wx.showToast({ 
            title: '解析结果失败', 
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('上传失败详情:', err)
        wx.showToast({ 
          title: `上传失败: ${err.errMsg}`,
          icon: 'none',
          duration: 3000
        })
        this.setData({ loading: false })
      }
    })
  },
  
  switchCamera: function() {
    this.setData({
      devicePosition: this.data.devicePosition === 'back' ? 'front' : 'back'
    })
  },
  
  retake: function() {
    this.setData({
      cameraActive: true,
      tempFilePath: '',
      result: null
    })
  }
})